import React, { Component } from 'react';

export default class UpdatedStatsBlock extends Component {
  static displayName = 'UpdatedStatsBlock';

  static propTypes = {};

  static defaultProps = {};

  timeoutId = '';

  constructor(props) {
    super(props);
    this.state = {
    	value: 0
    };
  }

  render() {
  	return (
      <div style={styles.todayCard}>
        <img src={this.props.image} alt="" style={styles.todayCardIcon} />
        <div>
          <div style={styles.label}>{this.props.label}</div>
          <div style={styles.value}>{this.state.value}</div>
        </div>
      </div>
  	)
  }

  componentDidMount() {
    if(this.props.api) {
      this.fetch()
    }
  }

  componentWillUnmount() {
    clearTimeout(this.timeoutId)
  }

  fetch() {
    let that = this;
    this.props.api().then(data => {
      next()
      that.setState({
        value: that.props.valueIndex ? (data.hasOwnProperty(that.props.valueIndex) ? data[that.props.valueIndex] : that.props.default) : data.data
      })
    }).catch(error => {
      next()
    })

    let next = ()=> {
      if(that.props.interval) {
        that.timeoutId = setTimeout(()=>{
          that.fetch();
        }, 3000)
      }
    }
    
  }
}

const styles = {
  cardTitle: {
    margin: '0 0 20px',
    fontSize: '18px',
    paddingBottom: '15px',
    fontWeight: 'bold',
    borderBottom: '1px solid #eee',
  },
  totalCard: {
    maxWidth: '160px',
    padding: '10px',
    borderRadius: '4px',
    color: '#fff',
  },
  todayCard: {
    display: 'flex',
    alignItems: 'center',
  },
  todayCardIcon: {
    width: '36px',
    height: '36px',
    marginRight: '8px',
  },
  label: {
    height: '14px',
    lineHeight: '14px',
    marginBottom: '8px',
  },
  value: {
    height: '28px',
    lineHeight: '28px',
    fontSize: '28px',
    fontWeight: '500',
  },
};